package com.ilink.groundservice.service.impl.AiX;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.PO.AiX.AiXArea;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneAuthor;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneBase;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneBeginEnd;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseBase;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseFinish;
import com.ilink.groundservice.entity.PO.AiX.AiXScenePhaseOpus;
import com.ilink.groundservice.entity.VO.AiX.AiXAuthorResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXScenePhaseSectionDTO;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneStartLearn;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneSubPhase;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneSubPhaseOpus;
import com.ilink.groundservice.entity.PO.AiX.AiXTag;
import com.ilink.groundservice.entity.PO.AiX.AiXTagConnect;
import com.ilink.groundservice.entity.VO.AiX.AiXScenePhaseOpusResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXScenePhaseTaskDTO;
import com.ilink.groundservice.entity.VO.AiX.AiXSceneResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXSceneSubPhaseOpusResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXScoreOpusResponse;
import com.ilink.groundservice.mapper.AiX.AiXAreaMapper;
import com.ilink.groundservice.mapper.AiX.AiXDeleteMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneAchievementMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneAuthorMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneBaseMapper;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseBaseMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneBeginEndMapper;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseFinishMapper;
import com.ilink.groundservice.mapper.AiX.AiXScenePhaseOpusMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneSignUpMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneStartLearnMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneSubPhaseOpusMapper;
import com.ilink.groundservice.mapper.AiX.AiXSceneSubPhaseMapper;
import com.ilink.groundservice.mapper.AiX.AiXTagConnectMapper;
import com.ilink.groundservice.mapper.AiX.AiXTagMapper;
import com.ilink.groundservice.service.AiX.AiXOpusService;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkapi.dto.ground.AiX.AiXAreaFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPhaseOpusInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPhaseOpusScoreRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXScenePhaseOpusGroundRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXSubPhaseOpusInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXSubPhaseOpusScoreRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.service.oss.MinioService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import com.ilink.ilinkcommon.utils.UserContext;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.ilinkcommon.utils.BeanUtils;


@Service
@Slf4j
@RequiredArgsConstructor
public class AiXOpusServiceImpl implements AiXOpusService {

    private final AiXScenePhaseBaseMapper aixScenePhaseBaseMapper;
    private final AiXSceneSubPhaseMapper aixSceneSubPhaseMapper;
    private final AiXSceneBeginEndMapper aixSceneBeginEndMapper;
    private final AiXSceneStartLearnMapper aixSceneStartLearnMapper;
    private final AiXScenePhaseFinishMapper aixScenePhaseFinishMapper;
    private final AiXScenePhaseOpusMapper aixScenePhaseOpusMapper;
    private final AiXSceneSubPhaseOpusMapper aixSceneSubPhaseOpusMapper;
    private final AiXSceneBaseMapper aixSceneBaseMapper;
    private final AiXAreaMapper aixAreaMapper;
    private final MinioService minioService;
    private final AiXTagMapper aiXTagMapper;
    private final AiXTagConnectMapper aiXTagConnectMapper;
    private final AiXSceneAuthorMapper aiXSceneAuthorMapper;
    private final UserServiceClient userServiceClient;
    private final AiXSceneBaseMapper aiXSceneBaseMapper;
    private final AiXSceneBeginEndMapper aiXSceneBeginEndMapper;
    @Override
    public AiXScenePhaseOpusResponse getPhaseOpus(Long phaseId, Long beginEndId, String userId) {
        // 根据beginEndId查AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId).eq(AiXSceneStartLearn::getUserId, userId).last("limit 1"));
        // 根据phaseid,startLearnId查phasefinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId()).last("limit 1"));
        if (phaseFinish == null) {
            return null;
        }
        // 根据phasefinish表的progressid查phaseopus表
        AiXScenePhaseOpus phaseOpus = aixScenePhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseOpus>().eq(AiXScenePhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXScenePhaseOpus::getUserId, userId).last("limit 1"));
        if (phaseOpus == null) {
            return null;
        }
        // 将查到的对象的coverurl和opusurl通过minio转为真实连接，构造响应
        AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
        response.setPhaseOpusId(phaseOpus.getPhaseOpusId());
        response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", phaseOpus.getCoverUrl()));
        response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", phaseOpus.getOpusUrl()));
        response.setProgressId(phaseFinish.getProgressId());
        response.setUserId(userId);
        response.setOpusTitle(phaseOpus.getOpusTitle());
        response.setIntroduction(phaseOpus.getIntroduction());
        response.setCommitTime(phaseOpus.getCommitTime());
        response.setScore(phaseOpus.getScore());
        response.setRemark(phaseOpus.getRemark());

        // 获取作品标签
        List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(
            new LambdaQueryWrapper<AiXTagConnect>()
                .eq(AiXTagConnect::getConnectTableKey, phaseOpus.getPhaseOpusId())
                .eq(AiXTagConnect::getConnectTable, "ai_x_scene_phase_opus")
        );
        List<String> tags = tagConnects.stream()
            .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
            .collect(Collectors.toList());
        response.setTags(tags);

        return response;
    }

    @Override
    @Transactional
    public R submitPhaseOpus(AiXPhaseOpusInsertRequest request, String userId) {
        // 首先根据phaseid到AiXScenePhaseBase表中查询phaseId是否有作业，如果没有返回R.error
        AiXScenePhaseBase phase = aixScenePhaseBaseMapper.selectById(request.getPhaseId());
        if (!phase.getWorkExist()) {
            return R.error("该阶段没有作业");
        }
        // 使用请求里的beginEndId查询AiXSceneBeginEnd表
        AiXSceneBeginEnd beginEnd = aixSceneBeginEndMapper.selectOne(new LambdaQueryWrapper<AiXSceneBeginEnd>().eq(AiXSceneBeginEnd::getBeginEndId, request.getBeginEndId()).last("limit 1"));
        if (beginEnd == null) {
            return R.error("未找到这一期课程，beginEndId：" + request.getBeginEndId());
        }
        // 同时使用beginEndid和userid查询AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEnd.getBeginEndId()).eq(AiXSceneStartLearn::getUserId, userId).last("limit 1"));
        if (startLearn == null) {
            return R.error("未找到当前用户开始学习记录，userId：" + userId);
        }
        // 查询是否有满足条件的phaseFinish，如果有，获取他的progressid，如果没有，新增
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, request.getPhaseId()).eq(AiXScenePhaseFinish::getUserId, userId).eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId()).last("limit 1"));
        if (phaseFinish == null) {
            phaseFinish = new AiXScenePhaseFinish();
            phaseFinish.setProgressId(new SnowflakeIdGenerator(1, 1).nextId());
            phaseFinish.setPhaseId(request.getPhaseId());
            phaseFinish.setUserId(userId);
            phaseFinish.setStartLearnId(startLearn.getStartLearnId());
            phaseFinish.setIsFinish(false);
            aixScenePhaseFinishMapper.insert(phaseFinish);
        }

        // 查询是否已存在作品记录
        AiXScenePhaseOpus existingOpus = aixScenePhaseOpusMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseOpus>()
                .eq(AiXScenePhaseOpus::getProgressId, phaseFinish.getProgressId())
                .eq(AiXScenePhaseOpus::getUserId, userId)
                .last("limit 1")
        );

        AiXScenePhaseOpus opus;
        if (existingOpus != null) {
            // 如果存在，使用现有记录
            opus = existingOpus;
            // 删除旧封面图和文件
            String coverUrl = existingOpus.getCoverUrl();
            String coverDirectory = coverUrl.substring(0, coverUrl.lastIndexOf('/') + 1);
            String coverFileName = getFileName(coverUrl);
            minioService.deleteBucketFile("dataset-square-migrate", coverDirectory, coverFileName);
            String opusUrl = existingOpus.getOpusUrl();
            String opusDirectory = opusUrl.substring(0, opusUrl.lastIndexOf('/') + 1);
            String opusFileName = getFileName(opusUrl);
            minioService.deleteBucketFile("dataset-square-migrate", opusDirectory, opusFileName);
        } else {
            // 如果不存在，创建新记录
            opus = new AiXScenePhaseOpus();
            opus.setPhaseOpusId(new SnowflakeIdGenerator(1, 1).nextId());
            opus.setProgressId(phaseFinish.getProgressId());
            opus.setUserId(userId);
        }

        // 更新作品信息
        opus.setOpusTitle(request.getOpusTitle());
        if (request.getIntroduction() == null || request.getIntroduction().isEmpty()) {
            opus.setIntroduction("学生未填写作业介绍");
        } else {
            opus.setIntroduction(request.getIntroduction());
        }
        AiXSceneBase scene = aixSceneBaseMapper.selectById(phase.getSceneId());
        AiXArea area = aixAreaMapper.selectById(scene.getAreaId());
        String coverUrl = "area/"+area.getAreaId()+"/scene/"+phase.getSceneId()+"/phase/"+request.getPhaseId()+"/opus/"+opus.getPhaseOpusId()+"_cover"+ getFileExtension(request.getCoverImage().getOriginalFilename());
        // 上传封面图片到 OSS
        if (request.getCoverImage().isEmpty()) {
            // 如果封面图为空，使用默认图片
            String defaultCoverUrl = minioService.getBucketFileUrl("dataset-square-migrate", "ai_x_public_assets/cover.png");
            boolean isCoverUploaded = minioService.downloadAndUpload("dataset-square-migrate", defaultCoverUrl, coverUrl+".png");
            if (!isCoverUploaded) {
                return R.error("默认封面图片下载上传失败");
            }
            opus.setCoverUrl(coverUrl+".png");
        } else {
            boolean isCoverUploaded = minioService.uploadBucketFile(request.getCoverImage(), "dataset-square-migrate", coverUrl);
            if (!isCoverUploaded) {
                return R.error("封面图片上传失败");
            }
            opus.setCoverUrl(coverUrl);
        }

        // 上传作业文件到 OSS
        opus.setOpusFileName(request.getOpusFile().getOriginalFilename());
        String opusFileUrl = "area/"+area.getAreaId()+"/scene/"+phase.getSceneId()+"/phase/"+request.getPhaseId()+"/opus/"+opus.getPhaseOpusId()+"_file"+ getFileExtension(request.getOpusFile().getOriginalFilename());
        boolean isFileUploaded = minioService.uploadBucketFile(request.getOpusFile(), "dataset-square-migrate", opusFileUrl);
        if (!isFileUploaded) {
            return R.error("作业文件上传失败");
        }
        opus.setOpusUrl(opusFileUrl);
        opus.setCommitTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        opus.setScore(0);
        opus.setRemark("待教师评价");

        // 根据是否存在记录决定插入还是更新
        if (existingOpus != null) {
            aixScenePhaseOpusMapper.updateById(opus);
        } else {
            aixScenePhaseOpusMapper.insert(opus);
        }

        boolean isPhaseFinished = isPhaseFinished(request.getPhaseId(), userId);
        if (isPhaseFinished) {
            // 查询出需要更新的对象
            AiXScenePhaseFinish finish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>()
                .eq(AiXScenePhaseFinish::getPhaseId, request.getPhaseId())
                .eq(AiXScenePhaseFinish::getUserId, userId)
                .eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId()));
            if (finish != null) {
                finish.setIsFinish(true);
                aixScenePhaseFinishMapper.updateById(finish);
            }
        }

        // 处理标签
        if (request.getTags() != null) {
            // 删除现有标签关联
            aiXTagConnectMapper.delete(new LambdaQueryWrapper<AiXTagConnect>()
                .eq(AiXTagConnect::getConnectTableKey, opus.getPhaseOpusId())
                .eq(AiXTagConnect::getConnectTable, "ai_x_scene_phase_opus"));

            // 处理新标签
            for (String tag : request.getTags()) {
                // 检查标签是否存在
                AiXTag existingTag = aiXTagMapper.selectOne(
                    new LambdaQueryWrapper<AiXTag>()
                        .eq(AiXTag::getTagName, tag)
                        .last("LIMIT 1")
                );

                Long tagId;
                if (existingTag == null) {
                    // 创建新标签
                    tagId = new SnowflakeIdGenerator(1, 1).nextId();
                    AiXTag newTag = new AiXTag();
                    newTag.setTagId(tagId);
                    newTag.setTagName(tag);
                    aiXTagMapper.insert(newTag);
                } else {
                    tagId = existingTag.getTagId();
                }

                // 创建关联
                AiXTagConnect tagConnect = new AiXTagConnect();
                tagConnect.setConnectId(new SnowflakeIdGenerator(1, 1).nextId());
                tagConnect.setConnectTable("ai_x_scene_phase_opus");
                tagConnect.setConnectTableKey(opus.getPhaseOpusId());
                tagConnect.setTagId(tagId);
                aiXTagConnectMapper.insert(tagConnect);
            }
        }

        return R.ok("提交阶段作业成功");
    }

    @Override
    @Transactional
    public R deletePhaseOpus(Long phaseId, Long beginEndId, String userId) {
        // 根据beginEndId查询AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId).eq(AiXSceneStartLearn::getUserId, userId).last("limit 1"));
        // 根据phaseid,startLearnId查询AiXScenePhaseFinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId()).last("limit 1"));
        if (phaseFinish == null) {
            return R.error("阶段完成记录不存在");
        }
        // 根据phasefinish表的progressid查询AiXScenePhaseOpus表
        AiXScenePhaseOpus phaseOpus = aixScenePhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseOpus>().eq(AiXScenePhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXScenePhaseOpus::getUserId, userId).last("limit 1"));
        // 如果phaseOpus为null，返回R.error
        if (phaseOpus == null || phaseOpus.getPhaseOpusId() == null) {
            return R.error("作品不存在");
        }
        // 删除封面图和文件
        String coverUrl = phaseOpus.getCoverUrl();
        String coverDirectory = coverUrl.substring(0, coverUrl.lastIndexOf('/') + 1);
        String coverFileName = getFileName(coverUrl);
        boolean isCoverDeleted = minioService.deleteBucketFile("dataset-square-migrate", coverDirectory, coverFileName);
        if (!isCoverDeleted) {
            return R.error("封面图删除失败");
        }
        String opusUrl = phaseOpus.getOpusUrl();
        String opusDirectory = opusUrl.substring(0, opusUrl.lastIndexOf('/') + 1);
        String opusFileName = getFileName(opusUrl);
        boolean isFileDeleted = minioService.deleteBucketFile("dataset-square-migrate", opusDirectory, opusFileName);
        if (!isFileDeleted) {
            return R.error("文件删除失败");
        }
        // 删除AiXScenePhaseOpus表的记录
        aixScenePhaseOpusMapper.deleteById(phaseOpus.getPhaseOpusId());
        // AiXScenePhaseFinish表的ISFINISH改为false
        phaseFinish.setIsFinish(false);
        aixScenePhaseFinishMapper.updateById(phaseFinish);

        // 删除标签关联
        aiXTagConnectMapper.delete(new LambdaQueryWrapper<AiXTagConnect>()
            .eq(AiXTagConnect::getConnectTableKey, phaseOpus.getPhaseOpusId())
            .eq(AiXTagConnect::getConnectTable, "ai_x_scene_phase_opus"));

        return R.ok("删除作品成功");
    }

    @Override
    public AiXSceneSubPhaseOpusResponse getSubPhaseOpus(Long subPhaseId, Long beginEndId, String userId) {
        // 根据beginEndId查询AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId).eq(AiXSceneStartLearn::getUserId, userId).last("limit 1"));
        // 根据subPhaseId查询所属的phaseId
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectById(subPhaseId);
        Long phaseId = subPhase.getPhaseId();
        // 根据phaseid,startLearnId查询AiXScenePhaseFinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getUserId, userId).last("limit 1"));
        if (phaseFinish == null) {
            return null;
        }
        // 根据phasefinish表的progressid和subphaseid查subPhaseOpus表
        AiXSceneSubPhaseOpus subPhaseOpus = aixSceneSubPhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXSceneSubPhaseOpus>().eq(AiXSceneSubPhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXSceneSubPhaseOpus::getSubPhaseId, subPhaseId).eq(AiXSceneSubPhaseOpus::getUserId, userId).last("limit 1"));
        if (subPhaseOpus == null) {
            return null;
        }
        // 将查到的对象的coverurl和opusurl通过minio转为真实连接，构造响应
        AiXSceneSubPhaseOpusResponse response = new AiXSceneSubPhaseOpusResponse();
        response.setSubPhaseOpusId(subPhaseOpus.getSubPhaseOpusId());
        response.setSubPhaseId(subPhaseOpus.getSubPhaseId());
        response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", subPhaseOpus.getCoverUrl()));
        response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", subPhaseOpus.getOpusUrl()));
        response.setProgressId(phaseFinish.getProgressId());
        response.setUserId(userId);
        response.setOpusTitle(subPhaseOpus.getOpusTitle());
        response.setIntroduction(subPhaseOpus.getIntroduction());
        response.setCommitTime(subPhaseOpus.getCommitTime());
        response.setScore(subPhaseOpus.getScore());
        response.setRemark(subPhaseOpus.getRemark());

        // 获取作品标签
        List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(
            new LambdaQueryWrapper<AiXTagConnect>()
                .eq(AiXTagConnect::getConnectTableKey, subPhaseOpus.getSubPhaseOpusId())
                .eq(AiXTagConnect::getConnectTable, "ai_x_scene_sub_phase_opus")
        );
        List<String> tags = tagConnects.stream()
            .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
            .collect(Collectors.toList());
        response.setTags(tags);

        return response;
    }

    @Override
    @Transactional
    public R submitSubPhaseOpus(AiXSubPhaseOpusInsertRequest request, String userId) {
        // 首先根据subPhaseId到AiXSceneSubPhase表中查询是否有作业
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectById(request.getSubPhaseId());
        if (!subPhase.getWorkExist()) {
            return R.error("该子阶段没有作业");
        }
        // 根据subPhaseid查询所属的phaseId
        Long phaseId = subPhase.getPhaseId();
        AiXScenePhaseBase phase = aixScenePhaseBaseMapper.selectById(phaseId);
        // 使用请求里的beginEndId查询AiXSceneBeginEnd表
        AiXSceneBeginEnd beginEnd = aixSceneBeginEndMapper.selectOne(new LambdaQueryWrapper<AiXSceneBeginEnd>().eq(AiXSceneBeginEnd::getBeginEndId, request.getBeginEndId()).last("limit 1"));
        // 同时使用beginEndid和userid查询AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(
            new LambdaQueryWrapper<AiXSceneStartLearn>()
                .eq(AiXSceneStartLearn::getBeginEndId, beginEnd.getBeginEndId())
                .eq(AiXSceneStartLearn::getUserId, userId)
                .last("limit 1")
        );
        if (startLearn == null) {
            return R.error("未找到当前用户开始学习记录，userId：" + userId);
        }

        // 查询是否有满足条件的phaseFinish，如果有，获取他的progressid，如果没有，新增
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseFinish>()
                .eq(AiXScenePhaseFinish::getPhaseId, subPhase.getPhaseId())
                .eq(AiXScenePhaseFinish::getUserId, userId)
                .eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId())
                .last("limit 1")
        );
        if (phaseFinish == null) {
            phaseFinish = new AiXScenePhaseFinish();
            phaseFinish.setProgressId(new SnowflakeIdGenerator(1, 1).nextId());
            phaseFinish.setPhaseId(phaseId);
            phaseFinish.setUserId(userId);
            phaseFinish.setStartLearnId(startLearn.getStartLearnId());
            phaseFinish.setIsFinish(false);
            aixScenePhaseFinishMapper.insert(phaseFinish);
        }

        // 查询是否已存在作品记录
        AiXSceneSubPhaseOpus existingOpus = aixSceneSubPhaseOpusMapper.selectOne(
            new LambdaQueryWrapper<AiXSceneSubPhaseOpus>()
                .eq(AiXSceneSubPhaseOpus::getProgressId, phaseFinish.getProgressId())
                .eq(AiXSceneSubPhaseOpus::getSubPhaseId, request.getSubPhaseId())
                .eq(AiXSceneSubPhaseOpus::getUserId, userId)
                .last("limit 1")
        );

        AiXSceneSubPhaseOpus opus;
        if (existingOpus != null) {
            // 如果存在，使用现有记录
            opus = existingOpus;
            // 删除旧封面图和文件
            String coverUrl = existingOpus.getCoverUrl();
            String coverDirectory = coverUrl.substring(0, coverUrl.lastIndexOf('/') + 1);
            String coverFileName = getFileName(coverUrl);
            minioService.deleteBucketFile("dataset-square-migrate", coverDirectory, coverFileName);
            String opusUrl = existingOpus.getOpusUrl();
            String opusDirectory = opusUrl.substring(0, opusUrl.lastIndexOf('/') + 1);
            String opusFileName = getFileName(opusUrl);
            minioService.deleteBucketFile("dataset-square-migrate", opusDirectory, opusFileName);
        } else {
            // 如果不存在，创建新记录
            opus = new AiXSceneSubPhaseOpus();
            opus.setSubPhaseOpusId(new SnowflakeIdGenerator(1, 1).nextId());
            opus.setProgressId(phaseFinish.getProgressId());
            opus.setSubPhaseId(request.getSubPhaseId());
            opus.setUserId(userId);
        }

        // 更新作品信息
        opus.setOpusTitle(request.getOpusTitle());
        if (request.getIntroduction() == null || request.getIntroduction().isEmpty()) {
            opus.setIntroduction("学生未填写作业介绍");
        } else {
            opus.setIntroduction(request.getIntroduction());
        }

        // 构建文件路径
        AiXSceneBase scene = aixSceneBaseMapper.selectById(phase.getSceneId());
        AiXArea area = aixAreaMapper.selectById(scene.getAreaId());
        String coverUrl = "area/" + area.getAreaId() + "/scene/" + scene.getSceneId() + "/phase/" + phase.getPhaseId() +
            "/subphase/" + request.getSubPhaseId() + "/opus/" + opus.getSubPhaseOpusId() + "_cover" +
            getFileExtension(request.getCoverImage().getOriginalFilename());

        // 上传封面图片到 OSS
        if (request.getCoverImage().isEmpty()) {
            // 如果封面图为空，使用默认图片
            String defaultCoverUrl = minioService.getBucketFileUrl("dataset-square-migrate", "ai_x_public_assets/cover.png");
            boolean isCoverUploaded = minioService.downloadAndUpload("dataset-square-migrate", defaultCoverUrl, coverUrl + ".png");
            if (!isCoverUploaded) {
                return R.error("默认封面图片下载上传失败");
            }
            opus.setCoverUrl(coverUrl + ".png");
        } else {
            boolean isCoverUploaded = minioService.uploadBucketFile(request.getCoverImage(), "dataset-square-migrate", coverUrl);
            if (!isCoverUploaded) {
                return R.error("封面图片上传失败");
            }
            opus.setCoverUrl(coverUrl);
        }

        // 上传作业文件到 OSS
        opus.setOpusFileName(request.getOpusFile().getOriginalFilename());
        String opusFileUrl = "area/" + area.getAreaId() + "/scene/" + scene.getSceneId() + "/phase/" + phase.getPhaseId() +
            "/subphase/" + request.getSubPhaseId() + "/opus/" + opus.getSubPhaseOpusId() + "_file" +
            getFileExtension(request.getOpusFile().getOriginalFilename());
        boolean isFileUploaded = minioService.uploadBucketFile(request.getOpusFile(), "dataset-square-migrate", opusFileUrl);
        if (!isFileUploaded) {
            return R.error("作业文件上传失败");
        }
        opus.setOpusUrl(opusFileUrl);
        opus.setCommitTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        opus.setScore(0);
        opus.setRemark("待教师评价");

        // 根据是否存在记录决定插入还是更新
        if (existingOpus != null) {
            aixSceneSubPhaseOpusMapper.updateById(opus);
        } else {
            aixSceneSubPhaseOpusMapper.insert(opus);
        }

        // 检查阶段是否完成并更新状态
        boolean isPhaseFinished = isPhaseFinished(subPhase.getPhaseId(), userId);
        if (isPhaseFinished) {
            AiXScenePhaseFinish finish = aixScenePhaseFinishMapper.selectOne(
                new LambdaQueryWrapper<AiXScenePhaseFinish>()
                    .eq(AiXScenePhaseFinish::getPhaseId, subPhase.getPhaseId())
                    .eq(AiXScenePhaseFinish::getUserId, userId)
                    .eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId())
            );
            if (finish != null) {
                finish.setIsFinish(true);
                aixScenePhaseFinishMapper.updateById(finish);
            }
        }

        // 处理标签
        if (request.getTags() != null) {
            // 删除现有标签关联
            aiXTagConnectMapper.delete(
                new LambdaQueryWrapper<AiXTagConnect>()
                    .eq(AiXTagConnect::getConnectTableKey, opus.getSubPhaseOpusId())
                    .eq(AiXTagConnect::getConnectTable, "ai_x_scene_sub_phase_opus")
            );

            // 处理新标签
            for (String tag : request.getTags()) {
                // 检查标签是否存在
                AiXTag existingTag = aiXTagMapper.selectOne(
                    new LambdaQueryWrapper<AiXTag>()
                        .eq(AiXTag::getTagName, tag)
                        .last("LIMIT 1")
                );

                Long tagId;
                if (existingTag == null) {
                    // 创建新标签
                    tagId = new SnowflakeIdGenerator(1, 1).nextId();
                    AiXTag newTag = new AiXTag();
                    newTag.setTagId(tagId);
                    newTag.setTagName(tag);
                    aiXTagMapper.insert(newTag);
                } else {
                    tagId = existingTag.getTagId();
                }

                // 创建关联
                AiXTagConnect tagConnect = new AiXTagConnect();
                tagConnect.setConnectId(new SnowflakeIdGenerator(1, 1).nextId());
                tagConnect.setConnectTable("ai_x_scene_sub_phase_opus");
                tagConnect.setConnectTableKey(opus.getSubPhaseOpusId());
                tagConnect.setTagId(tagId);
                aiXTagConnectMapper.insert(tagConnect);
            }
        }

        return R.ok("提交子阶段作业成功");
    }

    @Override
    @Transactional
    public R deleteSubPhaseOpus(Long subPhaseId, Long beginEndId, String userId) {
        // 根据subPhaseId查询所属的phaseId
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectById(subPhaseId);
        Long phaseId = subPhase.getPhaseId();
        // 根据beginEndId查询AiXSceneStartLearn表
        AiXSceneStartLearn startLearn = aixSceneStartLearnMapper.selectOne(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId).eq(AiXSceneStartLearn::getUserId, userId).last("limit 1"));
        // 根据phaseId,startLearnId查询AiXScenePhaseFinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getStartLearnId, startLearn.getStartLearnId()).last("limit 1"));
        if (phaseFinish == null) {
            return R.error("阶段完成记录不存在");
        }
        // 根据phasefinish表的progressid和subPhaseId查询AiXSceneSubPhaseOpus表
        AiXSceneSubPhaseOpus subPhaseOpus = aixSceneSubPhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXSceneSubPhaseOpus>().eq(AiXSceneSubPhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXSceneSubPhaseOpus::getSubPhaseId, subPhaseId).eq(AiXSceneSubPhaseOpus::getUserId, userId).last("limit 1"));
        // 如果phaseOpus为null，返回R.error
        if (subPhaseOpus == null|| subPhaseOpus.getSubPhaseOpusId() == null) {
            return R.error("作品不存在");
        }
        // 删除封面图和文件
        String coverUrl = subPhaseOpus.getCoverUrl();
        String coverDirectory = coverUrl.substring(0, coverUrl.lastIndexOf('/') + 1);
        String coverFileName = getFileName(coverUrl);
        boolean isCoverDeleted = minioService.deleteBucketFile("dataset-square-migrate", coverDirectory, coverFileName);
        if (!isCoverDeleted) {
            return R.error("封面图删除失败");
        }
        String opusUrl = subPhaseOpus.getOpusUrl();
        String opusDirectory = opusUrl.substring(0, opusUrl.lastIndexOf('/') + 1);
        String opusFileName = getFileName(opusUrl);
        boolean isFileDeleted = minioService.deleteBucketFile("dataset-square-migrate", opusDirectory, opusFileName);
        if (!isFileDeleted) {
            return R.error("文件删除失败");
        }
        // 删除AiXSceneSubPhaseOpus表的记录
        aixSceneSubPhaseOpusMapper.deleteById(subPhaseOpus.getSubPhaseOpusId());
        // AiXScenePhaseFinish表的ISFINISH改为false
        phaseFinish.setIsFinish(false);
        aixScenePhaseFinishMapper.updateById(phaseFinish);

        // 删除标签关联
        aiXTagConnectMapper.delete(new LambdaQueryWrapper<AiXTagConnect>()
            .eq(AiXTagConnect::getConnectTableKey, subPhaseOpus.getSubPhaseOpusId())
            .eq(AiXTagConnect::getConnectTable, "ai_x_scene_sub_phase_opus"));

        return R.ok("删除子阶段作品成功");
    }

    @Override
    public List<AiXScenePhaseOpusResponse> getAllPhaseOpus(Long phaseId, Long beginEndId) {
        // 根据beginendid查询startlearn数据， 得到一个userid的列表
        List<AiXSceneStartLearn> startLearns = aixSceneStartLearnMapper.selectList(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId));
        List<String> userIds = startLearns.stream().map(AiXSceneStartLearn::getUserId).collect(Collectors.toList());

        // 如果没有用户ID，直接返回空列表
        if (userIds.isEmpty()) {
            return new ArrayList<>(); // 返回空列表
        }

        // 根据phaseid和userid列表查询AiXScenePhaseFinish表， 得到一个progressid列表
        List<AiXScenePhaseFinish> phaseFinishes = aixScenePhaseFinishMapper.selectList(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).in(AiXScenePhaseFinish::getUserId, userIds));
        List<Long> progressIds = phaseFinishes.stream().map(AiXScenePhaseFinish::getProgressId).collect(Collectors.toList());

        // 如果没有进度ID，直接返回空列表
        if (progressIds.isEmpty()) {
            return new ArrayList<>(); // 返回空列表
        }

        // 根据progressid列表查询AiXScenePhaseOpus表， 得到一个AiXScenePhaseOpusResponse的列表
        List<AiXScenePhaseOpus> phaseOpuses = aixScenePhaseOpusMapper.selectList(new LambdaQueryWrapper<AiXScenePhaseOpus>().in(AiXScenePhaseOpus::getProgressId, progressIds));

        // 将phaseOpuses列表转换为AiXScenePhaseOpusResponse列表
        List<AiXScenePhaseOpusResponse> phaseOpusesResponse = phaseOpuses.stream().map(phaseOpus -> {
            AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
            response.setPhaseOpusId(phaseOpus.getPhaseOpusId());
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", phaseOpus.getCoverUrl()));
            response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", phaseOpus.getOpusUrl()));
            response.setProgressId(phaseOpus.getProgressId());
            response.setUserId(phaseOpus.getUserId());
            response.setOpusTitle(phaseOpus.getOpusTitle());
            response.setIntroduction(phaseOpus.getIntroduction());
            response.setCommitTime(phaseOpus.getCommitTime());
            response.setScore(phaseOpus.getScore());
            response.setRemark(phaseOpus.getRemark());

            // 获取作品标签
            List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(
                new LambdaQueryWrapper<AiXTagConnect>()
                    .eq(AiXTagConnect::getConnectTableKey, phaseOpus.getPhaseOpusId())
                    .eq(AiXTagConnect::getConnectTable, "ai_x_scene_phase_opus")
            );
            List<String> tags = tagConnects.stream()
                .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
                .collect(Collectors.toList());
            response.setTags(tags);

            return response;
        }).collect(Collectors.toList());

        return phaseOpusesResponse;
    }

    @Override
    public List<AiXSceneSubPhaseOpusResponse> getAllSubPhaseOpus(Long subPhaseId, Long beginEndId) {
        // 根据beginendid查询startlearn数据， 得到一个userid的列表
        List<AiXSceneStartLearn> startLearns = aixSceneStartLearnMapper.selectList(new LambdaQueryWrapper<AiXSceneStartLearn>().eq(AiXSceneStartLearn::getBeginEndId, beginEndId));
        List<String> userIds = startLearns.stream().map(AiXSceneStartLearn::getUserId).collect(Collectors.toList());
        // 根据subPhaseId查询所属的phaseId
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectById(subPhaseId);
        Long phaseId = subPhase.getPhaseId();
        // 根据phaseid和userid列表查询AiXScenePhaseFinish表， 得到一个progressid列表
        List<AiXScenePhaseFinish> phaseFinishes = aixScenePhaseFinishMapper.selectList(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).in(AiXScenePhaseFinish::getUserId, userIds));
        List<Long> progressIds = phaseFinishes.stream().map(AiXScenePhaseFinish::getProgressId).collect(Collectors.toList());
        // 根据progressid列表查询AiXSceneSubPhaseOpus表， 得到一个AiXSceneSubPhaseOpusResponse的列表
        List<AiXSceneSubPhaseOpus> subPhaseOpuses = aixSceneSubPhaseOpusMapper.selectList(new LambdaQueryWrapper<AiXSceneSubPhaseOpus>().in(AiXSceneSubPhaseOpus::getProgressId, progressIds));
        // 将subPhaseOpuses列表转换为AiXSceneSubPhaseOpusResponse列表
        List<AiXSceneSubPhaseOpusResponse> subPhaseOpusesResponse = subPhaseOpuses.stream().map(subPhaseOpus -> {
            AiXSceneSubPhaseOpusResponse response = new AiXSceneSubPhaseOpusResponse();
            response.setSubPhaseOpusId(subPhaseOpus.getSubPhaseOpusId());
            response.setSubPhaseId(subPhaseOpus.getSubPhaseId());
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", subPhaseOpus.getCoverUrl()));
            response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", subPhaseOpus.getOpusUrl()));
            response.setProgressId(subPhaseOpus.getProgressId());
            response.setUserId(subPhaseOpus.getUserId());
            response.setOpusTitle(subPhaseOpus.getOpusTitle());
            response.setIntroduction(subPhaseOpus.getIntroduction());
            response.setCommitTime(subPhaseOpus.getCommitTime());
            response.setScore(subPhaseOpus.getScore());
            response.setRemark(subPhaseOpus.getRemark());

            // 获取作品标签
            List<AiXTagConnect> tagConnects = aiXTagConnectMapper.selectList(
                new LambdaQueryWrapper<AiXTagConnect>()
                    .eq(AiXTagConnect::getConnectTableKey, subPhaseOpus.getSubPhaseOpusId())
                    .eq(AiXTagConnect::getConnectTable, "ai_x_scene_sub_phase_opus")
            );
            List<String> tags = tagConnects.stream()
                .map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
                .collect(Collectors.toList());
            response.setTags(tags);

            return response;
        }).collect(Collectors.toList());
        return subPhaseOpusesResponse;
    }

    @Override
    @Transactional
    public R scorePhaseOpus(AiXPhaseOpusScoreRequest request) {
        // 根据request里的phaseid和userid查询AiXScenePhaseFinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, request.getPhaseId()).eq(AiXScenePhaseFinish::getUserId, request.getUserId()).last("limit 1"));
        if (phaseFinish == null) {
            return R.error("阶段完成记录不存在");
        }
        // 根据phasefinish表的progressid查询AiXScenePhaseOpus表
        AiXScenePhaseOpus phaseOpus = aixScenePhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseOpus>().eq(AiXScenePhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXScenePhaseOpus::getUserId, request.getUserId()).last("limit 1"));
        if (phaseOpus == null) {
            return R.error("阶段作品不存在");
        }
        // 根据phaseid查询AiXScenePhaseBase表，得到其中的work_score字段，如果request.getScore大于work_score，则报错分数超过上限
        AiXScenePhaseBase phase = aixScenePhaseBaseMapper.selectById(request.getPhaseId());
        if (request.getScore() > phase.getWorkScore()) {
            return R.error("分数超过上限");
        }
        // 更新AiXScenePhaseOpus表的score和remark
        phaseOpus.setScore(request.getScore());
        phaseOpus.setRemark(request.getRemark());
        aixScenePhaseOpusMapper.updateById(phaseOpus);
        AiXScoreOpusResponse response = new AiXScoreOpusResponse();
        response.setUserId(request.getUserId());
        response.setScore(request.getScore());
        response.setRemark(request.getRemark());
        return R.ok("阶段作品评分成功",response);
    }

    @Override
    @Transactional
    public R scoreSubPhaseOpus(AiXSubPhaseOpusScoreRequest request) {
        // 根据subphaseid查询所属的phaseid
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectById(request.getSubPhaseId());
        Long phaseId = subPhase.getPhaseId();
        // 根据phaseid和userid查询AiXScenePhaseFinish表
        AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getUserId, request.getUserId()).last("limit 1"));
        if (phaseFinish == null) {
            return R.error("阶段完成记录不存在");
        }
        // 根据phasefinish表的progressid和subphaseid查询AiXSceneSubPhaseOpus表
        AiXSceneSubPhaseOpus subPhaseOpus = aixSceneSubPhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXSceneSubPhaseOpus>().eq(AiXSceneSubPhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXSceneSubPhaseOpus::getSubPhaseId, request.getSubPhaseId()).eq(AiXSceneSubPhaseOpus::getUserId, request.getUserId()).last("limit 1"));
        if (subPhaseOpus == null) {
            return R.error("子阶段作品不存在");
        }
        // 根据work_score字段，如果request.getScore大于work_score，则报错分数超过上限
        if (request.getScore() > subPhase.getWorkScore()) {
            return R.error("分数超过上限");
        }
        // 更新AiXSceneSubPhaseOpus表的score和remark
        subPhaseOpus.setScore(request.getScore());
        subPhaseOpus.setRemark(request.getRemark());
        aixSceneSubPhaseOpusMapper.updateById(subPhaseOpus);
        AiXScoreOpusResponse response = new AiXScoreOpusResponse();
        response.setUserId(request.getUserId());
        response.setScore(request.getScore());
        response.setRemark(request.getRemark());
        return R.ok("子阶段作品评分成功",response);
    }


    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return dotIndex == -1 ? "" : fileName.substring(dotIndex);
    }

    private String getFileName(String url) {
        int lastSlashIndex = url.lastIndexOf('/');
        return url.substring(lastSlashIndex + 1);
    }

    // 判断阶段作业是否全部已完成
    private boolean isPhaseFinished(Long phaseId, String userId) {
        // 根据phaseid到AiXScenePhaseBase表中查询phaseId是否有作业
        AiXScenePhaseBase phase = aixScenePhaseBaseMapper.selectById(phaseId);
        // 如果有作业，到作品里查询是否有一条记录
        if (phase.getWorkExist()) {
            // 根据phaseid查询phasefinish表的progressid
            AiXScenePhaseFinish phaseFinish = aixScenePhaseFinishMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, phaseId).eq(AiXScenePhaseFinish::getUserId, userId).last("limit 1"));
            // 根据progressid查询AiXScenePhaseOpus表的opusid
            AiXScenePhaseOpus opus = aixScenePhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXScenePhaseOpus>().eq(AiXScenePhaseOpus::getProgressId, phaseFinish.getProgressId()).eq(AiXScenePhaseOpus::getUserId, userId).last("limit 1"));
            if (opus == null) {
                return false;
            }
        }

        // 然后判断这个阶段对应的子阶段有哪几个有作业
        List<AiXSceneSubPhase> subPhases = aixSceneSubPhaseMapper.selectList(new LambdaQueryWrapper<AiXSceneSubPhase>().eq(AiXSceneSubPhase::getPhaseId, phaseId));
        for (AiXSceneSubPhase subPhase : subPhases) {
            if (subPhase.getWorkExist()) {
                // 根据subPhaseId和userId查询subPhaseOpus表是否有这一条记录
                AiXSceneSubPhaseOpus subPhaseOpus = aixSceneSubPhaseOpusMapper.selectOne(new LambdaQueryWrapper<AiXSceneSubPhaseOpus>().eq(AiXSceneSubPhaseOpus::getSubPhaseId, subPhase.getSubPhaseId()).eq(AiXSceneSubPhaseOpus::getUserId, userId).last("limit 1"));
                if (subPhaseOpus == null) {
                    return false;
                }
            }
        }


        return true;
    }
    @Override
    public IPage<AiXScenePhaseOpusResponse> getOpusGround(AiXAreaFilterRequest request) {
        // 创建阶段分页
        Page<AiXScenePhaseOpus> phasePage = new Page<>(request.getPage(), request.getSize());
        LambdaQueryWrapper<AiXScenePhaseOpus> phaseQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AiXSceneSubPhaseOpus> subPhaseQueryWrapper = new LambdaQueryWrapper<>();

        // 根据关键词过滤阶段作品
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            phaseQueryWrapper.and(wrapper -> wrapper.like(AiXScenePhaseOpus::getOpusTitle, request.getKeyword())
                .or().like(AiXScenePhaseOpus::getIntroduction, request.getKeyword()));
            subPhaseQueryWrapper.and(wrapper -> wrapper.like(AiXSceneSubPhaseOpus::getOpusTitle, request.getKeyword())
                .or().like(AiXSceneSubPhaseOpus::getIntroduction, request.getKeyword()));
        }

        // 如果指定了区域ID，需要先获取该区域下的所有场景ID
        if (request.getAreaId() != null) {
            List<AiXSceneBase> scenes = aixSceneBaseMapper.selectList(
                new LambdaQueryWrapper<AiXSceneBase>()
                    .eq(AiXSceneBase::getAreaId, request.getAreaId())
            );
            List<Long> sceneIds = scenes.stream()
                .map(AiXSceneBase::getSceneId)
                .collect(Collectors.toList());

            if (sceneIds.isEmpty()) {
                // 如果该区域下没有场景，直接返回空结果
                return new Page<>(request.getPage(), request.getSize());
            }

            // 获取这些场景下的所有阶段ID
            List<AiXScenePhaseBase> phases = aixScenePhaseBaseMapper.selectList(
                new LambdaQueryWrapper<AiXScenePhaseBase>()
                    .in(AiXScenePhaseBase::getSceneId, sceneIds)
            );
            List<Long> phaseIds = phases.stream()
                .map(AiXScenePhaseBase::getPhaseId)
                .collect(Collectors.toList());

            // 获取这些阶段下的所有子阶段ID
            List<AiXSceneSubPhase> subPhases = aixSceneSubPhaseMapper.selectList(
                new LambdaQueryWrapper<AiXSceneSubPhase>()
                    .in(AiXSceneSubPhase::getPhaseId, phaseIds)
            );
            List<Long> subPhaseIds = subPhases.stream()
                .map(AiXSceneSubPhase::getSubPhaseId)
                .collect(Collectors.toList());

            // 在原有的查询条件基础上添加阶段ID和子阶段ID的筛选
            if (!phaseIds.isEmpty()) {
                // 获取这些阶段的完成记录
                List<AiXScenePhaseFinish> phaseFinishes = aixScenePhaseFinishMapper.selectList(
                    new LambdaQueryWrapper<AiXScenePhaseFinish>()
                        .in(AiXScenePhaseFinish::getPhaseId, phaseIds)
                );
                List<Long> progressIds = phaseFinishes.stream()
                    .map(AiXScenePhaseFinish::getProgressId)
                    .collect(Collectors.toList());

                if (!progressIds.isEmpty()) {
                    phaseQueryWrapper.in(AiXScenePhaseOpus::getProgressId, progressIds);
                } else {
                    phaseQueryWrapper.eq(AiXScenePhaseOpus::getProgressId, -1L); // 确保查不到数据
                }
            } else {
                phaseQueryWrapper.eq(AiXScenePhaseOpus::getProgressId, -1L); // 确保查不到数据
            }

            if (!subPhaseIds.isEmpty()) {
                subPhaseQueryWrapper.in(AiXSceneSubPhaseOpus::getSubPhaseId, subPhaseIds);
            } else {
                subPhaseQueryWrapper.eq(AiXSceneSubPhaseOpus::getSubPhaseId, -1L); // 确保查不到数据
            }
        }

        // 查询阶段作品数据
        IPage<AiXScenePhaseOpus> phaseOpusPage = aixScenePhaseOpusMapper.selectPage(phasePage, phaseQueryWrapper);
        List<AiXScenePhaseOpusResponse> responseList = phaseOpusPage.getRecords().stream().map(opus -> {
            AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
            response.setPhaseOpusId(opus.getPhaseOpusId());
            response.setProgressId(opus.getProgressId());
            response.setUserId(opus.getUserId());
            response.setOpusFileName(opus.getOpusFileName());
            response.setOpusTitle(opus.getOpusTitle());
            response.setIntroduction(opus.getIntroduction());
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", opus.getCoverUrl()));
            response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", opus.getOpusUrl()));
            response.setCommitTime(opus.getCommitTime());
            response.setScore(opus.getScore());
            response.setRemark(opus.getRemark());

            // 获取阶段作品标签
            List<String> tags = aiXTagConnectMapper.selectList(new LambdaQueryWrapper<AiXTagConnect>()
                    .eq(AiXTagConnect::getConnectTableKey, opus.getPhaseOpusId())
                    .eq(AiXTagConnect::getConnectTable, "ai_x_scene_phase_opus"))
                .stream().map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
                .collect(Collectors.toList());
            response.setTags(tags);

            return response;
        }).collect(Collectors.toList());

        // 查询子阶段作品数据
        List<AiXScenePhaseOpusResponse> subPhaseResponses = aixSceneSubPhaseOpusMapper.selectList(subPhaseQueryWrapper).stream().map(subOpus -> {
            AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
            response.setPhaseOpusId(subOpus.getSubPhaseOpusId());
            response.setProgressId(subOpus.getProgressId());
            response.setOpusFileName(subOpus.getOpusFileName());
            response.setUserId(subOpus.getUserId());
            response.setOpusTitle(subOpus.getOpusTitle());
            response.setIntroduction(subOpus.getIntroduction());
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", subOpus.getCoverUrl()));
            response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", subOpus.getOpusUrl()));
            response.setCommitTime(subOpus.getCommitTime());
            response.setScore(subOpus.getScore());
            response.setRemark(subOpus.getRemark());

            // 获取子阶段作品标签
            List<String> tags = aiXTagConnectMapper.selectList(new LambdaQueryWrapper<AiXTagConnect>()
                    .eq(AiXTagConnect::getConnectTableKey, subOpus.getSubPhaseOpusId())
                    .eq(AiXTagConnect::getConnectTable, "ai_x_scene_sub_phase_opus"))
                .stream().map(tagConnect -> aiXTagMapper.selectById(tagConnect.getTagId()).getTagName())
                .collect(Collectors.toList());
            response.setTags(tags);

            return response;
        }).collect(Collectors.toList());

        // 合并阶段作品和子阶段作品
        responseList.addAll(subPhaseResponses);

        // 根据标签过滤结果
        if (request.getTag() != null && !request.getTag().isEmpty()) {
            responseList = responseList.stream()
                .filter(response -> response.getTags().contains(request.getTag()))
                .collect(Collectors.toList());
            log.info("根据标签筛选后的作品总数: {}", responseList.size());
        }

        // 构造最终分页对象
        Page<AiXScenePhaseOpusResponse> responsePage = new Page<>(phaseOpusPage.getCurrent(), phaseOpusPage.getSize(), phaseOpusPage.getTotal() + subPhaseResponses.size());
        responsePage.setRecords(responseList);

        log.info("阶段作品和子阶段作品合并后的总数: {}", responseList.size());
        return responsePage;
    }

    @Override
    public IPage<AiXScenePhaseOpusResponse> getOpusGroundForAuthor(AiXScenePhaseOpusGroundRequest request) {
        // 创建阶段分页对象
        Page<AiXScenePhaseOpus> phasePage = new Page<>(request.getPage(), request.getSize());
        LambdaQueryWrapper<AiXScenePhaseOpus> phaseQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AiXSceneSubPhaseOpus> subPhaseQueryWrapper = new LambdaQueryWrapper<>();

        // 根据关键词过滤阶段作品和子阶段作品
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            phaseQueryWrapper.and(wrapper -> wrapper.like(AiXScenePhaseOpus::getOpusTitle, request.getKeyword())
                .or().like(AiXScenePhaseOpus::getIntroduction, request.getKeyword()));
            subPhaseQueryWrapper.and(wrapper -> wrapper.like(AiXSceneSubPhaseOpus::getOpusTitle, request.getKeyword())
                .or().like(AiXSceneSubPhaseOpus::getIntroduction, request.getKeyword()));
        }

        // 使用传入的 subPhaseId 作为查询条件：
        // 1. 在 ai_x_scene_phase_finish 表中，用 subPhaseId 作为 phaseId 查询对应的 progress_id 列表，
        //    然后用这些 progress_id 在阶段作品表中查询阶段作品数据
        if (request.getSubPhaseId() != null && request.getSubPhaseId() > 0) {
            List<AiXScenePhaseFinish> phaseFinishes = aixScenePhaseFinishMapper.selectList(
                new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getPhaseId, request.getSubPhaseId())
            );
            List<Long> progressIds = phaseFinishes.stream()
                .map(AiXScenePhaseFinish::getProgressId)
                .collect(Collectors.toList());
            if (!progressIds.isEmpty()) {
                phaseQueryWrapper.in(AiXScenePhaseOpus::getProgressId, progressIds);
            } else {
                // 如果没有查到进度ID，则确保查询不到数据
                phaseQueryWrapper.eq(AiXScenePhaseOpus::getProgressId, -1L);
            }
        }

        // 2. 根据传入的 subPhaseId 查询子阶段作品数据
        if (request.getSubPhaseId() != null && request.getSubPhaseId() > 0) {
            subPhaseQueryWrapper.eq(AiXSceneSubPhaseOpus::getSubPhaseId, request.getSubPhaseId());
        }

        // 查询阶段作品数据
        IPage<AiXScenePhaseOpus> phaseOpusPage = aixScenePhaseOpusMapper.selectPage(phasePage, phaseQueryWrapper);
        List<AiXScenePhaseOpusResponse> responseList = phaseOpusPage.getRecords().stream().map(opus -> {
            AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
            response.setPhaseOpusId(opus.getPhaseOpusId());
            response.setProgressId(opus.getProgressId());
            response.setUserId(opus.getUserId());
            response.setOpusFileName(opus.getOpusFileName());
            response.setOpusTitle(opus.getOpusTitle());
            response.setIntroduction(opus.getIntroduction());
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", opus.getCoverUrl()));
            response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", opus.getOpusUrl()));
            response.setCommitTime(opus.getCommitTime());
            response.setScore(opus.getScore());
            response.setRemark(opus.getRemark());
            // 获取阶段对应的场景标题
            String sceneTitle = getSceneTitleByPhaseOpus(opus);
            response.setTags(Collections.singletonList(sceneTitle));
            return response;
        }).collect(Collectors.toList());

        // 查询子阶段作品数据
        List<AiXScenePhaseOpusResponse> subPhaseResponses = aixSceneSubPhaseOpusMapper.selectList(subPhaseQueryWrapper)
            .stream().map(subOpus -> {
                AiXScenePhaseOpusResponse response = new AiXScenePhaseOpusResponse();
                response.setPhaseOpusId(subOpus.getSubPhaseOpusId());
                response.setProgressId(subOpus.getProgressId());
                response.setUserId(subOpus.getUserId());
                response.setOpusFileName(subOpus.getOpusFileName());
                response.setOpusTitle(subOpus.getOpusTitle());
                response.setIntroduction(subOpus.getIntroduction());
                response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", subOpus.getCoverUrl()));
                response.setOpusUrl(minioService.getBucketFileUrl("dataset-square-migrate", subOpus.getOpusUrl()));
                response.setCommitTime(subOpus.getCommitTime());
                response.setScore(subOpus.getScore());
                response.setRemark(subOpus.getRemark());
                // 获取子阶段对应的场景标题
                String sceneTitle = getSceneTitleBySubPhaseOpus(subOpus);
                response.setTags(Collections.singletonList(sceneTitle));
                return response;
            }).collect(Collectors.toList());

        // 合并阶段和子阶段作品数据
        responseList.addAll(subPhaseResponses);

        // 构造最终分页对象：采用阶段作品分页信息，再加上子阶段作品数量
        Page<AiXScenePhaseOpusResponse> responsePage = new Page<>(phaseOpusPage.getCurrent(), phaseOpusPage.getSize(),
            phaseOpusPage.getTotal() + subPhaseResponses.size());
        responsePage.setRecords(responseList);

        log.info("阶段作品和子阶段作品合并后的总数: {}", responseList.size());
        return responsePage;
    }


    // 根据阶段作品记录获取所属微场景的标题
    private String getSceneTitleByPhaseOpus(AiXScenePhaseOpus opus) {
        // 通过 progress_id 查询阶段完成记录
        AiXScenePhaseFinish finish = aixScenePhaseFinishMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseFinish>().eq(AiXScenePhaseFinish::getProgressId, opus.getProgressId())
        );
        if (finish == null) {
            return "";
        }
        // 通过 finish 中的 phase_id 查询阶段基础记录
        AiXScenePhaseBase phaseBase = aixScenePhaseBaseMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseBase>().eq(AiXScenePhaseBase::getPhaseId, finish.getPhaseId())
        );
        if (phaseBase == null) {
            return "";
        }
        // 通过 phaseBase 中的 sceneId 查询微场景记录
        AiXSceneBase scene = aixSceneBaseMapper.selectOne(
            new LambdaQueryWrapper<AiXSceneBase>().eq(AiXSceneBase::getSceneId, phaseBase.getSceneId())
        );
        return scene != null ? scene.getSceneTitle() : "";
    }

    // 根据子阶段作品记录获取所属微场景的标题
    private String getSceneTitleBySubPhaseOpus(AiXSceneSubPhaseOpus subOpus) {
        // 根据 subPhaseId 查询子阶段记录
        AiXSceneSubPhase subPhase = aixSceneSubPhaseMapper.selectOne(
            new LambdaQueryWrapper<AiXSceneSubPhase>().eq(AiXSceneSubPhase::getSubPhaseId, subOpus.getSubPhaseId())
        );
        if (subPhase == null) {
            return "";
        }
        // 根据子阶段记录中的 phaseId 查询阶段基础记录
        AiXScenePhaseBase phaseBase = aixScenePhaseBaseMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseBase>().eq(AiXScenePhaseBase::getPhaseId, subPhase.getPhaseId())
        );
        if (phaseBase == null) {
            return "";
        }
        // 根据阶段基础记录中的 sceneId 查询微场景记录
        AiXSceneBase scene = aixSceneBaseMapper.selectOne(
            new LambdaQueryWrapper<AiXSceneBase>().eq(AiXSceneBase::getSceneId, phaseBase.getSceneId())
        );
        return scene != null ? scene.getSceneTitle() : "";
    }


    @Override
    public List<String> getAuthorTags(String userId) {
        List<Long> sceneIds = aiXSceneAuthorMapper.selectList(
            new LambdaQueryWrapper<AiXSceneAuthor>()
                .eq(AiXSceneAuthor::getUserId, userId)
        ).stream().map(AiXSceneAuthor::getSceneId).collect(Collectors.toList());

        // 根据场景ID查询对应的sceneTitle
        List<AiXSceneBase> scenes = aixSceneBaseMapper.selectList(
            new LambdaQueryWrapper<AiXSceneBase>().in(AiXSceneBase::getSceneId, sceneIds)
        );

        // 提取所有场景的标题
        return scenes.stream()
            .map(AiXSceneBase::getSceneTitle)
            .collect(Collectors.toList());
    }

    @Override
    public List<AiXScenePhaseSectionDTO> getCourseSections(Long sceneId) {
        // 根据场景ID查询对应的阶段记录，同时要求 phaseId 不为空
        List<AiXScenePhaseBase> sections = aixScenePhaseBaseMapper.selectList(
            new LambdaQueryWrapper<AiXScenePhaseBase>()
                .eq(AiXScenePhaseBase::getSceneId, sceneId)
                .isNotNull(AiXScenePhaseBase::getPhaseId)
        );

        // 提取每条记录中的 phaseTitle 和 phaseId，封装到 DTO 中返回
        List<AiXScenePhaseSectionDTO> result = sections.stream()
            .map(section -> {
                AiXScenePhaseSectionDTO dto = new AiXScenePhaseSectionDTO();
                dto.setPhaseTitle(section.getPhaseTitle());
                dto.setPhaseId(section.getPhaseId());
                return dto;
            })
            .collect(Collectors.toList());

        return result;
    }

    @Override
    public List<AiXScenePhaseTaskDTO> getCourseTasks(Long phaseId) {
        List<AiXScenePhaseTaskDTO> taskList = new ArrayList<>();

        // 1. 查询子阶段任务：从 ai_x_scene_sub_phase 表中获取 sub_phase_title 和 sub_phase_id
        List<AiXSceneSubPhase> subPhases = aixSceneSubPhaseMapper.selectList(
            new LambdaQueryWrapper<AiXSceneSubPhase>().eq(AiXSceneSubPhase::getPhaseId, phaseId)
        );
        if (subPhases != null && !subPhases.isEmpty()) {
            // 对每个子阶段记录，创建新的 DTO
            for (AiXSceneSubPhase subPhase : subPhases) {
                AiXScenePhaseTaskDTO dto = new AiXScenePhaseTaskDTO();
                dto.setSubPhaseTitle(subPhase.getSubPhaseTitle());
                dto.setSubPhaseId(subPhase.getSubPhaseId());
                taskList.add(dto);
            }
        }

        // 2. 查询阶段基本信息：从 ai_x_scene_phase_base 表中获取该阶段的 work_requirement（阶段作品）
        AiXScenePhaseBase phaseBase = aixScenePhaseBaseMapper.selectOne(
            new LambdaQueryWrapper<AiXScenePhaseBase>().eq(AiXScenePhaseBase::getPhaseId, phaseId)
        );
        if (phaseBase != null && phaseBase.getWorkRequirement() != null && !phaseBase.getWorkRequirement().isEmpty()) {
            AiXScenePhaseTaskDTO dto = new AiXScenePhaseTaskDTO();
            // 当阶段存在作品时，返回的标题直接为“阶段作品”
            dto.setSubPhaseTitle("阶段作品");
            // 阶段作品时，subPhaseId 返回阶段的 phaseId
            dto.setSubPhaseId(phaseBase.getPhaseId());
            taskList.add(dto);
        }

        return taskList;
    }

    @Override
    public IPage<AiXSceneResponse> getCourses(AiXAreaFilterRequest request, String userId) {
        // 获取用户关联的场景ID集合
        List<Long> authorizedSceneIds = aiXSceneAuthorMapper.selectList(
            new LambdaQueryWrapper<AiXSceneAuthor>().eq(AiXSceneAuthor::getUserId, userId)
        ).stream().map(AiXSceneAuthor::getSceneId).collect(Collectors.toList());
        if (authorizedSceneIds.isEmpty()) {
            return new Page<>(request.getPage(), request.getSize());
        }
        // 构建分页与查询条件
        Page<AiXSceneBase> page = new Page<>(request.getPage(), request.getSize());
        LambdaQueryWrapper<AiXSceneBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(AiXSceneBase::getSceneId, authorizedSceneIds);

        // 应用区域过滤
        Optional.ofNullable(request.getAreaId())
            .ifPresent(areaId -> queryWrapper.eq(AiXSceneBase::getAreaId, areaId));

        // 处理标签过滤
        if (StringUtils.isNotBlank(request.getTag())) {
            Long tagId = Optional.ofNullable(aiXTagMapper.selectOne(
                    new LambdaQueryWrapper<AiXTag>().eq(AiXTag::getTagName, request.getTag())))
                .map(AiXTag::getTagId).orElse(null);
            if (tagId != null) {
                List<Long> tagSceneIds = aiXTagConnectMapper.selectList(
                        new LambdaQueryWrapper<AiXTagConnect>().eq(AiXTagConnect::getTagId, tagId))
                    .stream().map(AiXTagConnect::getConnectTableKey).collect(Collectors.toList());
                List<Long> filteredIds = authorizedSceneIds.stream()
                    .filter(tagSceneIds::contains).collect(Collectors.toList());
                if (filteredIds.isEmpty()) {
                    return new Page<>(request.getPage(), request.getSize());
                }
                queryWrapper.in(AiXSceneBase::getSceneId, filteredIds);
            }
        }

        // 实现关键词模糊查询
        if (StringUtils.isNotBlank(request.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like(AiXSceneBase::getSceneTitle, request.getKeyword())
                .or().like(AiXSceneBase::getIntroduction, request.getKeyword()));
        }

        // 执行分页查询
        IPage<AiXSceneBase> scenePage = aiXSceneBaseMapper.selectPage(page, queryWrapper);

        // 数据转换处理
        return scenePage.convert(scene -> {
            AiXSceneResponse response = new AiXSceneResponse();
            BeanUtils.copyProperties(scene, response);
            response.setCoverUrl(minioService.getBucketFileUrl("dataset-square-migrate", scene.getCoverUrl()));

            // 设置出品人信息
            response.setAuthors(aiXSceneAuthorMapper.selectList(
                    new LambdaQueryWrapper<AiXSceneAuthor>().eq(AiXSceneAuthor::getSceneId, scene.getSceneId()))
                .stream().map(author -> getUserInfoById(author.getUserId()))
                .filter(Objects::nonNull).collect(Collectors.toList()));

            // 设置标签数据
            response.setTags(aiXTagConnectMapper.selectList(
                    new LambdaQueryWrapper<AiXTagConnect>().eq(AiXTagConnect::getConnectTableKey, scene.getSceneId()))
                .stream().map(tc -> aiXTagMapper.selectById(tc.getTagId()).getTagName())
                .collect(Collectors.toList()));

            // 设置时间范围
            Optional.ofNullable(aiXSceneBeginEndMapper.selectOne(
                    new LambdaQueryWrapper<AiXSceneBeginEnd>()
                        .eq(AiXSceneBeginEnd::getSceneId, scene.getSceneId())))
                .ifPresent(beginEnd -> {
                    response.setStartTime(beginEnd.getStartTime());
                    response.setEndTime(beginEnd.getEndTime());
                });
            return response;
        });
    }
    private AiXAuthorResponse getUserInfoById(String userId) {
        // 获取用户信息
        R whoami = userServiceClient.whoami(userId);
        HttpStatus status = HttpStatus.valueOf(whoami.getCode());

        if (!status.is2xxSuccessful()) {
            log.error(String.format("获取用户信息失败，用户ID: %s", userId));
            return null; // 如果获取用户信息失败，返回 null
        }

        // 获取用户详细信息
        User userDetail = BeanUtils.copyBean(whoami.getData(), User.class);

        // 将用户信息映射到 AiXAuthorResponse
        AiXAuthorResponse authorResponse = new AiXAuthorResponse();
        authorResponse.setUserId(userDetail.getUserId());
        authorResponse.setNickname(userDetail.getNickname());
        authorResponse.setSchoolName(userDetail.getSchoolName());
        authorResponse.setEmail(userDetail.getEmail());
        authorResponse.setSchoolId(userDetail.getSchoolId());
        authorResponse.setUserIntroduction(userDetail.getUserIntroduction());
        authorResponse.setUserImage(userDetail.getUserImage());
        authorResponse.setUserCollege(userDetail.getUserCollege());
        authorResponse.setUserType(userDetail.getUserType());
        authorResponse.setRealname(userDetail.getRealname());
        authorResponse.setSex(userDetail.getSex());
        authorResponse.setUserGrade(userDetail.getUserGrade());
        authorResponse.setUserMajor(userDetail.getUserMajor());
        authorResponse.setUserMobile(userDetail.getUserMobile());
        authorResponse.setUserCover(userDetail.getUserCover());

        return authorResponse;  // 返回包含所有信息的 AiXAuthorResponse 对象
    }
}
